package com.zeyi.chat.controller;

import com.alibaba.fastjson.JSON;
import com.zeyi.chat.dto.Chat;
import com.zeyi.chat.dto.Message;
import com.zeyi.chat.manager.StageManager;
import com.zeyi.chat.manager.UserManager;
import com.zeyi.chat.po.ChatGroup;
import com.zeyi.chat.po.User;
import com.zeyi.chat.utils.SocketUtil;
import com.zeyi.chat.views.Alert;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;

import java.util.List;

/**
 * @author zeyi
 */
public class EditGroupInfoController {
    private static EditGroupInfoController instance;

    @FXML
    private TextField name;

    private ChatGroup group;

    public static EditGroupInfoController getInstance() {
        return instance;
    }

    @FXML
    private void initialize() {
        instance = this;
    }

    @FXML
    public void onClose(MouseEvent mouseEvent) {
        Stage stage = (Stage) name.getScene().getWindow();
        stage.close();
    }

    @FXML
    public void saveInfo(MouseEvent mouseEvent) {
        Stage stage = (Stage) name.getScene().getWindow();
        if (name.getText().equals("")) {
            new Alert("群名不能为空", stage);
            return;
        }
        User currentUser = UserManager.getCurrentUser();
        List<Chat> chatList = currentUser.getChatList();
        for (int i = 0; i < chatList.size(); i++) {
            Chat chat = chatList.get(i);
            if (chat.getCreateId() != null && chat.getId().equals(group.getId())) {
                HomeController.getInstance().updateGroup(new ChatGroup(chat.getId(), name.getText(), null));
                chat.setChatName(name.getText());
                break;
            }
        }
        group.setGroupName(name.getText());
        ChatInfoController.getInstance().displayGroupInfo(group, true);
        SocketUtil.send(new Message("ChatHandler/updateGroupInfo", JSON.toJSONString(group)));
        stage.close();
    }

    public void initData(ChatGroup group) {
        this.group = group;
        name.setText(group.getGroupName());
    }

}
